package com.hsylient.test;

public class OddEvenPrinterSync {

    private static final int MAX_PRINT_COUNT = 10;

    private int concurrentCount = 0;


    private void print1() {
        while (true) {
            synchronized (this) {
                if (concurrentCount < MAX_PRINT_COUNT) {
                    if (concurrentCount % 2 == 0) {
                        try {
                            wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    } else {
                        System.out.println(Thread.currentThread().getName() + concurrentCount);
                        concurrentCount++;
                        notifyAll();
                    }
                } else {
                    break;
                }
            }
        }

    }

    private void print2() {
        while (true) {
            synchronized (this) {
                if (concurrentCount < MAX_PRINT_COUNT) {
                    if (concurrentCount % 2 == 0) {
                        System.out.println(Thread.currentThread().getName() + concurrentCount);
                        concurrentCount++;
                        notifyAll();
                    } else {
                        try {
                            wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                } else {
                    break;
                }
            }
        }

    }

    public static void main(String[] args) throws InterruptedException {
        OddEvenPrinterSync oddEvenPrinterSync = new OddEvenPrinterSync();
        Thread t1 = new Thread(oddEvenPrinterSync::print1, "奇数线程");
        Thread t2 = new Thread(oddEvenPrinterSync::print2, "偶数线程");
        t1.start();
        t2.start();

        /*
         * join() 就是“等某个线程干完再干”，它让调用线程阻塞，直到目标线程执行完或超时。
         * 这里是main方法所在的主线程阻塞，然后等t1线程和t2线程执行完成才继续执行
         * t2.join(2000); // 最多等 2 秒 这里即使 t2 没执行完，main 也会在 2 秒后继续。
         */
        t1.join();
        t2.join();

        System.out.println("两个线程轮流打印奇偶数完成。。。");
    }
}
